<template>
  <div class="hello">
    <label for="uds-server">uds-server</label>：
    <input
      name="uds-server"
      type="button"
      value="uds-server"
      v-on:click="udsServer"
    />

    <label for="uds-client">uds-client</label>：
    <input
      name="uds-client"
      type="button"
      value="uds-client"
      v-on:click="udsClient"
    />
  </div>
</template>

<script>
var os = require("os");

var path = require("path");

var net = require("net");

// 配置中文简体环境下，完整的时间格式
const formatter = new Intl.DateTimeFormat("zh-CN", {
  year: "numeric",
  month: "long",
  day: "2-digit",
  hour: "2-digit",
  minute: "2-digit",
  second: "2-digit",
  fractionalSecondDigits: 3, // 包含毫秒
  hour12: false, // 使用24小时制
});

export default {
  name: "HelloWorld",
  props: {
    msg: String,
  },
  methods: {
    // server
    udsServer() {
      // uds server
      const server = net.createServer((socket) => {
        console.log("session connected.");

        // on data event
        socket.on("data", (data) => {
          console.log(" Received session data：", data.toString("utf-8"));

          socket.write("uds web server.");
        });

        // on end
        socket.on("end", () => {
          console.log("uds session end.");
        });

        // on error
        socket.on("error", (error) => {
          console.log("uds session error：", error);
        });
      });

      // windows、linux temp path
      var sockfile = this.getOSTempPath();

      // listen
      server.listen(sockfile, () => {});
    },
    // client
    udsClient() {
      // uds client
      const client = net.createConnection(
        {
          path: this.getOSTempPath(),
        },
        () => {
          console.log("connected to uds server.");
        }
      );

      // on connected
      client.on("connect", () => {
        console.log("uds connect");
      });

      // on error
      client.on("error", (err) => {
        console.log(err);
      });

      // on data
      client.on("data", (data) => {
        var now = new Date();
        console.log(
          `${formatter.format(now)} => client received data:${data.toString(
            "utf-8"
          )}`
        );
      });

      // on end
      client.on("end", () => {
        console.log("uds end");
      });

      client.write(formatter.format(new Date()));
    },
    getOSTempPath() {
      // windows、linux
      if (os.platform() === "win32") {
        return path.join("\\\\?\\pipe\\", "chat.sock");

        // return path.join(os.tmpdir(), "chat.sock");
      } else if (os.platform() === "linux") return "/tmp/chat.socket";
    },
  },
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h3 {
  margin: 40px 0 0;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
}
a {
  color: #42b983;
}
</style>
